﻿#include "ScreenshotOverlay.h"

ScreenshotOverlay::ScreenshotOverlay(QWidget *parent)
    : QWidget(parent), m_isSelecting(false), m_isResizing(false), m_isDragging(false), m_resizeHandle(NoHandle)
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground);
    setMouseTracking(true);

    // 获取所有屏幕的几何信息
    QRect totalGeometry;
    for (QScreen *screen : QGuiApplication::screens()) {
        totalGeometry = totalGeometry.united(screen->geometry());
    }

    setGeometry(totalGeometry);
    grabKeyboard();

    // 截取整个屏幕的快照
    m_fullScreenshot = QApplication::primaryScreen()->grabWindow(0);

    // 创建按钮
    setupButtons();
}

ScreenshotOverlay::~ScreenshotOverlay() {
    qDebug() << "ScreenshotOverlay destroyed";
}

void ScreenshotOverlay::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制半透明背景
    painter.fillRect(rect(), QColor(0, 0, 0, 100));

    if (m_selectionRect.isValid()) {
        // 绘制选中的区域（不透明）
        painter.drawPixmap(m_selectionRect, m_fullScreenshot, m_selectionRect);

        // 绘制选择边框
        painter.setPen(QPen(Qt::red, 2));
        painter.drawRect(m_selectionRect.adjusted(0, 0, -1, -1));

        // 绘制尺寸信息
        QString sizeText = QString("%1 x %2").arg(m_selectionRect.width()).arg(m_selectionRect.height());
        QFont font = painter.font();
        font.setPointSize(10);
        painter.setFont(font);
        painter.setPen(Qt::white);
        painter.drawText(m_selectionRect.bottomRight() + QPoint(5, 15), sizeText);

        // 绘制调整手柄
        drawResizeHandles(painter);
    } else if (m_isSelecting) {
        // 绘制选择中的矩形
        painter.setPen(QPen(Qt::red, 2));
        painter.drawRect(QRect(m_selectionStartPoint, m_selectionCurrentPoint));
    }

    // 显示按钮
    if (m_selectionRect.isValid()) {
        m_buttonWidget->show();
        // 将按钮放置在选区下方
        QPoint buttonPos(
            m_selectionRect.x() + (m_selectionRect.width() - m_buttonWidget->width()) / 2,
            m_selectionRect.y() + m_selectionRect.height() + 10
            );

        // 确保按钮不会超出屏幕
        if (buttonPos.y() + m_buttonWidget->height() > height()) {
            buttonPos.setY(m_selectionRect.y() - m_buttonWidget->height() - 10);
        }
        if (buttonPos.x() + m_buttonWidget->width() > width()) {
            buttonPos.setX(width() - m_buttonWidget->width() - 10);
        }
        if (buttonPos.x() < 0) {
            buttonPos.setX(10);
        }

        m_buttonWidget->move(buttonPos);
    } else {
        m_buttonWidget->hide();
    }
}

void ScreenshotOverlay::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        if (m_selectionRect.isValid()) {
            // 检查是否点击了调整手柄
            m_resizeHandle = getResizeHandle(event->pos());

            if (m_resizeHandle != NoHandle) {
                m_isResizing = true;
                m_resizeStartPoint = event->pos();
                m_resizeStartRect = m_selectionRect;
            } else if (m_selectionRect.contains(event->pos())) {
                // 开始拖动现有选区
                m_isDragging = true;
                m_dragOffset = event->pos() - m_selectionRect.topLeft();
            } else {
                // 开始新的选择
                startNewSelection(event->pos());
            }
        } else {
            // 开始新的选择
            startNewSelection(event->pos());
        }
        update();
    }
}

void ScreenshotOverlay::mouseMoveEvent(QMouseEvent *event)
{
    if (m_isSelecting) {
        m_selectionCurrentPoint = event->pos();
        update();
    } else if (m_isResizing) {
        handleResize(event->pos());
        update();
    } else if (m_isDragging) {
        QPoint newTopLeft = event->pos() - m_dragOffset;

        // 确保选区不会移出屏幕
        newTopLeft.setX(qMax(0, qMin(newTopLeft.x(), width() - m_selectionRect.width())));
        newTopLeft.setY(qMax(0, qMin(newTopLeft.y(), height() - m_selectionRect.height())));

        m_selectionRect.moveTo(newTopLeft);
        update();
    } else if (m_selectionRect.isValid()) {
        // 更新光标形状
        ResizeHandle handle = getResizeHandle(event->pos());
        updateCursor(handle);
    }
}

void ScreenshotOverlay::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        if (m_isSelecting) {
            // 结束选择，固定选区
            m_isSelecting = false;
            m_selectionCurrentPoint = event->pos();

            // 确保选区有效
            QRect newRect = QRect(m_selectionStartPoint, m_selectionCurrentPoint).normalized();
            if (newRect.width() >= 10 && newRect.height() >= 10) {
                m_selectionRect = newRect;
            } else {
                // 如果选区太小，设置为最小尺寸
                m_selectionRect = QRect(m_selectionStartPoint, m_selectionStartPoint + QPoint(100, 100));
            }

            qDebug() << "Selection fixed at:" << m_selectionRect;
            update();
        } else if (m_isResizing) {
            m_isResizing = false;
            m_resizeHandle = NoHandle;
        } else if (m_isDragging) {
            m_isDragging = false;
        }
    }
}

void ScreenshotOverlay::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_Escape:
        emit cancelled();
        break;
    case Qt::Key_Return:
    case Qt::Key_Enter:
        if (m_selectionRect.isValid()) {
            QPixmap screenshot = getScreenshot();
            emit accepted(screenshot);
        }
        break;
    default:
        QWidget::keyPressEvent(event);
    }
}

void ScreenshotOverlay::setupButtons()
{
    m_buttonWidget = new QWidget(this);
    m_buttonWidget->setStyleSheet("QWidget { background-color: rgba(50, 50, 50, 200); border-radius: 5px; }");

    QHBoxLayout *layout = new QHBoxLayout(m_buttonWidget);
    layout->setSpacing(5);
    layout->setContentsMargins(5, 5, 5, 5);

    QPushButton *saveButton = new QPushButton("保存");
    saveButton->setStyleSheet("QPushButton { background-color: #4CAF50; color: white; border: none; padding: 5px 10px; border-radius: 3px; }");
    connect(saveButton, &QPushButton::clicked, [this]() {
        QPixmap screenshot = getScreenshot();
        emit saveRequested(screenshot);
    });

    QPushButton *cancelButton = new QPushButton("取消");
    cancelButton->setStyleSheet("QPushButton { background-color: #f44336; color: white; border: none; padding: 5px 10px; border-radius: 3px; }");
    connect(cancelButton, &QPushButton::clicked, this, &ScreenshotOverlay::cancelled);

    QPushButton *okButton = new QPushButton("确认");
    okButton->setStyleSheet("QPushButton { background-color: #2196F3; color: white; border: none; padding: 5px 10px; border-radius: 3px; }");
    connect(okButton, &QPushButton::clicked, [this]() {
        QPixmap screenshot = getScreenshot();
        emit accepted(screenshot);
    });

    layout->addWidget(saveButton);
    layout->addWidget(cancelButton);
    layout->addWidget(okButton);

    m_buttonWidget->setLayout(layout);
    m_buttonWidget->adjustSize();
    m_buttonWidget->hide();
}

void ScreenshotOverlay::startNewSelection(const QPoint &pos)
{
    m_isSelecting = true;
    m_selectionStartPoint = pos;
    m_selectionCurrentPoint = pos;
    m_selectionRect = QRect();
    m_buttonWidget->hide();
    qDebug() << "Starting new selection at:" << pos;
}

QPixmap ScreenshotOverlay::getScreenshot() const
{
    if (m_selectionRect.isValid()) {
        return m_fullScreenshot.copy(m_selectionRect);
    }
    return QPixmap();
}

void ScreenshotOverlay::updateCursor(ResizeHandle handle)
{
    switch (handle) {
    case TopLeft:
    case BottomRight:
        setCursor(Qt::SizeFDiagCursor);
        break;
    case TopRight:
    case BottomLeft:
        setCursor(Qt::SizeBDiagCursor);
        break;
    case Top:
    case Bottom:
        setCursor(Qt::SizeVerCursor);
        break;
    case Left:
    case Right:
        setCursor(Qt::SizeHorCursor);
        break;
    case NoHandle:
        if (m_selectionRect.contains(mapFromGlobal(QCursor::pos()))) {
            setCursor(Qt::SizeAllCursor);
        } else {
            setCursor(Qt::CrossCursor);
        }
        break;
    }
}

void ScreenshotOverlay::drawResizeHandles(QPainter &painter)
{
    painter.setPen(QPen(Qt::white, 1));
    painter.setBrush(QBrush(Qt::red));

    const int handleSize = 6;
    const int handleMargin = 3;

    // 绘制四个角的手柄
    painter.drawRect(QRect(m_selectionRect.topLeft() - QPoint(handleMargin, handleMargin),
                           QSize(handleSize, handleSize)));
    painter.drawRect(QRect(m_selectionRect.topRight() + QPoint(-handleSize + handleMargin, -handleMargin),
                           QSize(handleSize, handleSize)));
    painter.drawRect(QRect(m_selectionRect.bottomLeft() + QPoint(-handleMargin, -handleSize + handleMargin),
                           QSize(handleSize, handleSize)));
    painter.drawRect(QRect(m_selectionRect.bottomRight() + QPoint(-handleSize + handleMargin, -handleSize + handleMargin),
                           QSize(handleSize, handleSize)));

    // 绘制四边中间的手柄
    painter.drawRect(QRect(QPoint(m_selectionRect.center().x() - handleSize/2, m_selectionRect.top() - handleMargin),
                           QSize(handleSize, handleSize)));
    painter.drawRect(QRect(QPoint(m_selectionRect.center().x() - handleSize/2, m_selectionRect.bottom() - handleSize + handleMargin),
                           QSize(handleSize, handleSize)));
    painter.drawRect(QRect(QPoint(m_selectionRect.left() - handleMargin, m_selectionRect.center().y() - handleSize/2),
                           QSize(handleSize, handleSize)));
    painter.drawRect(QRect(QPoint(m_selectionRect.right() - handleSize + handleMargin, m_selectionRect.center().y() - handleSize/2),
                           QSize(handleSize, handleSize)));
}

void ScreenshotOverlay::handleResize(const QPoint &pos)
{
    QRect newRect = m_resizeStartRect;

    switch (m_resizeHandle) {
    case TopLeft:
        newRect.setTopLeft(pos);
        break;
    case Top:
        newRect.setTop(pos.y());
        break;
    case TopRight:
        newRect.setTopRight(pos);
        break;
    case Left:
        newRect.setLeft(pos.x());
        break;
    case Right:
        newRect.setRight(pos.x());
        break;
    case BottomLeft:
        newRect.setBottomLeft(pos);
        break;
    case Bottom:
        newRect.setBottom(pos.y());
        break;
    case BottomRight:
        newRect.setBottomRight(pos);
        break;
    default:
        return;
    }

    // 确保选区不会太小
    if (newRect.width() < 10) {
        if (m_resizeHandle == Left || m_resizeHandle == TopLeft || m_resizeHandle == BottomLeft) {
            newRect.setLeft(newRect.right() - 10);
        } else {
            newRect.setRight(newRect.left() + 10);
        }
    }

    if (newRect.height() < 10) {
        if (m_resizeHandle == Top || m_resizeHandle == TopLeft || m_resizeHandle == TopRight) {
            newRect.setTop(newRect.bottom() - 10);
        } else {
            newRect.setBottom(newRect.top() + 10);
        }
    }

    // 确保选区不会超出屏幕
    newRect = newRect.intersected(rect());

    m_selectionRect = newRect;
}

ScreenshotOverlay::ResizeHandle ScreenshotOverlay::getResizeHandle(const QPoint &pos) const
{
    if (!m_selectionRect.isValid()) return NoHandle;

    const int handleSize = 8;
    const int handleMargin = 4;

    QRect handleRect;

    // 左上角
    handleRect = QRect(m_selectionRect.topLeft() - QPoint(handleMargin, handleMargin),
                       QSize(handleSize, handleSize));
    if (handleRect.contains(pos)) return TopLeft;

    // 上边
    handleRect = QRect(QPoint(m_selectionRect.center().x() - handleSize/2, m_selectionRect.top() - handleMargin),
                       QSize(handleSize, handleSize));
    if (handleRect.contains(pos)) return Top;

    // 右上角
    handleRect = QRect(m_selectionRect.topRight() + QPoint(-handleSize + handleMargin, -handleMargin),
                       QSize(handleSize, handleSize));
    if (handleRect.contains(pos)) return TopRight;

    // 左边
    handleRect = QRect(QPoint(m_selectionRect.left() - handleMargin, m_selectionRect.center().y() - handleSize/2),
                       QSize(handleSize, handleSize));
    if (handleRect.contains(pos)) return Left;

    // 右边
    handleRect = QRect(QPoint(m_selectionRect.right() - handleSize + handleMargin, m_selectionRect.center().y() - handleSize/2),
                       QSize(handleSize, handleSize));
    if (handleRect.contains(pos)) return Right;

    // 左下角
    handleRect = QRect(m_selectionRect.bottomLeft() + QPoint(-handleMargin, -handleSize + handleMargin),
                       QSize(handleSize, handleSize));
    if (handleRect.contains(pos)) return BottomLeft;

    // 下边
    handleRect = QRect(QPoint(m_selectionRect.center().x() - handleSize/2, m_selectionRect.bottom() - handleSize + handleMargin),
                       QSize(handleSize, handleSize));
    if (handleRect.contains(pos)) return Bottom;

    // 右下角
    handleRect = QRect(m_selectionRect.bottomRight() + QPoint(-handleSize + handleMargin, -handleSize + handleMargin),
                       QSize(handleSize, handleSize));
    if (handleRect.contains(pos)) return BottomRight;

    return NoHandle;
}
